#include "link_else_loongson_dialog.h"
#include "ui_link_else_loongson_dialog.h"
#include <QHostInfo>

QString link_else_loongson_dialog::getLocalIP()
{
    QString host_name = QHostInfo::localHostName();     //获取主机名
    QHostInfo host_info = QHostInfo::fromName(host_name);
    QList<QHostAddress> address = host_info.addresses();
    QString localIP;

    foreach(auto aHost,address)
    {
        if(aHost.protocol() == QAbstractSocket::IPv4Protocol)
        {
            localIP = aHost.toString();
        }
    }

    return localIP;
}

link_else_loongson_dialog::link_else_loongson_dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::link_else_loongson_dialog)
{
    ui->setupUi(this);

    this->socket = new QTcpSocket(this);    //创建套接字
    ui->ip_addr_edit->setText(getLocalIP());
    ui->send_data_btn->setDisabled(true);

    connect(socket,&QTcpSocket::connected,this,&link_else_loongson_dialog::on_connected);
    connect(socket,&QTcpSocket::disconnected,this,&link_else_loongson_dialog::on_disconnected);
}

link_else_loongson_dialog::~link_else_loongson_dialog()
{
    delete ui;
}

/* 连接服务器成功槽函数 */
void link_else_loongson_dialog::on_connected()
{
    qDebug() << "connect else loongson ok" << endl;
    ui->send_data_btn->setEnabled(true);
    ui->connect_btn->setDisabled(true);
    ui->disconnect_btn->setEnabled(true);
}

/* 连接其他龙芯派 */
void link_else_loongson_dialog::on_connect_btn_clicked()
{
    qDebug() << ui->ip_addr_edit->text();
    qDebug() << ui->lineEdit->text().toInt() << endl;
    socket->connectToHost(ui->ip_addr_edit->text(),ui->lineEdit->text().toUInt());    //连接服务器
}

void link_else_loongson_dialog::on_disconnected()
{
    ui->connect_btn->setEnabled(true);
    ui->disconnect_btn->setDisabled(true);
}

/* 断开连接 */
void link_else_loongson_dialog::on_disconnect_btn_clicked()
{
    socket->disconnectFromHost();
}

/* 清空接收区 */
void link_else_loongson_dialog::on_rd_edit_cle_btn_clicked()
{
    ui->recv_data_edit->clear();
}

/* 发送消息 */
void link_else_loongson_dialog::on_send_data_btn_clicked()
{
    QString send_data = ui->send_data_edit->toPlainText();
    socket->write(send_data.toUtf8());
}
